<template>
  <div class="login">
    <el-card shadow="hover" class="login-card">
      <div class="login-card-content">
        <div class="login-card-content-left">
          <img src="../../assets/login-logo.png" class="login-card-logo">
        </div>
        <div class="login-card-content-right">
          <el-form ref="loginForm" :model="loginForm" class="login-form" :rules="loginRules" label-width="0px">
            <h3 class="login-card-title">跨境电商ERP 后台管理系统</h3>
            <el-form-item prop="email" class="login-form-item">
              <el-input v-model="loginForm.email" placeholder="请输入邮箱">
                <span slot="prefix" class="login-form-prefix email" />
              </el-input>
            </el-form-item>
            <el-form-item prop="password" class="login-form-item">
              <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password @keyup.enter.native="handleLogin">
                <span slot="prefix" class="login-form-prefix password" />
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :loading="loading" class="login-card-btn" @click.native.prevent="handleLogin">登录</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import router from '@/router/index'
export default {
  name: 'Login',
  data() {
    /** const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 5) {
        callback(new Error('The password can not be less than 5 digits'))
      } else {
        callback()
      }
    }*/
    return {
      componentName: 'Login',
      loginForm: {
        email: '', // erp@admin.com
        password: '' // erpadmin
      },
      loginRules: {
        email: [
          {
            required: true,
            type: 'email',
            message: '请输入正确的账户邮箱',
            trigger: 'blur'
          }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: '',
      otherQuery: {}
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.email === '') {
      // this.$refs.email.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && key >= 'A' && key <= 'Z'
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store
            .dispatch('user/login', this.loginForm)
            .then(async () => {
              this.$store.commit('sidebarsub/SET_CURRENT_ROUTE', {})
              this.$store.commit('sidebarsub/SET_HIDE', false)
              const { roles, permissions } = await this.$store.dispatch('user/getInfo')
              // generate accessible routes map based on roles
              const accessRoutes = await this.$store.dispatch('permission/generateRoutes', [roles, permissions])
              const firstRouter = accessRoutes[0]
              this.redirect = firstRouter.children.length > 0 ? firstRouter.children[0].path : firstRouter.path
              accessRoutes.push({
                path: '/',
                redirect: this.redirect
              })
              router.addRoutes(accessRoutes)
              this.handleSelect(accessRoutes, firstRouter.path)
              this.$router.push({
                path: this.redirect || '/',
                query: this.otherQuery
              })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 把选中路由的子路由保存store
    handleSelect(routes, key) {
      const vm = this
      const route = routes.find((item) => item.path === key)
      this.$store.commit('sidebarsub/SET_CURRENT_ROUTE', route)
      this.setSidebarHide(route)
    },
    // 设置侧边栏的显示和隐藏
    setSidebarHide(route) {
      // console.log('===route.children==', route.children)
      //  || route.children.length === 1
      if (!route.children || route.children[0].path === '/dashboard') {
        this.$store.commit('sidebarsub/SET_HIDE', false)
      } else {
        this.$store.commit('', true)
      }
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
  }
}
</script>

<style lang="scss" scoped>
.login {
  height: 100%;
  background: url("../../assets/login-bg.png") no-repeat center 0px;
  background-size: cover;
  background-position: center 0;
  background-repeat: no-repeat;
  background-attachment: fixed;
  -webkit-background-size: cover;
  -o-background-size: cover;
  -moz-background-size: cover;
  -ms-background-size: cover;
  position: relative;
  &-card {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 998px;
    height: 607px;
    border-radius: 8px;
    background-color: rgba($color: #ffffff, $alpha: 0.9);
    &-content-left {
      position: absolute;
      left: 25px;
      top: 149px;
    }
    &-content-right {
      margin-left: 573px;
      margin-right: 70px;
      padding: 117px 0px 0;
    }
    &-logo {
      width: 471px;
      height: 304px;
    }
    &-title {
      font-size: 28px;
      font-weight: bold;
      color: #3a679b;
      text-align: center;
      margin: 0;
      margin-bottom: 37px;
    }
    &-btn {
      width: 100%;
      height: 56px;
      font-size: 22px;
      border-radius: 10px;
    }
  }
  &-form {
    &-item {
      margin-bottom: 30px;
    }
    &-prefix {
      width: 24px;
      height: 24px;
      display: inline-block;
      background-size: 100% 100%;
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }
    &-prefix.email {
      background-image: url("../../assets/login-form-email.png");
    }
    &-prefix.password {
      background-image: url("../../assets/login-form-password.png");
    }
  }
}
.login .login-card ::v-deep .el-card__body {
  padding: 0;
}
.login .login-card .login-form ::v-deep .el-form-item__content {
  line-height: 56px;
}
.login .login-card .login-form ::v-deep .el-input__inner {
  line-height: 56px;
  height: 56px;
  padding-left: 67px;
  font-size: 16px;
  border-radius: 10px;
  border: none;
  background-color: #f6f7fb;
}
.login .login-card .login-form ::v-deep .el-input__prefix {
  left: 18px;
}
// 按钮修改
.el-button--primary,
.el-button--primary:hover,
.el-button--primary:focus {
  background: #7ca4d2;
  border-color: #7ca4d2;
  color: #ffffff;
}
</style>
